package com.orangelife.mobile.login.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.curry.android.http.OrangeHttpBiz;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.orangelife.mobile.R;
import com.common.jump.CommonJumper;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.service.MyService;
import com.orangelife.mobile.main.biz.MainHttpBz;
import com.thirdsdk.jpush.JPushTagHelper;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.activity.PullRefreshBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.login.adapter.SelectCommunityListViewAdapter;
import com.orangelife.mobile.login.biz.CommunityHttpBiz;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 选择小区
 *
 * @author yw
 */
public class SelectCommunityActivity extends PullRefreshBaseActivity implements
        OnClickListener {
    /**
     * 选择小区标题
     */
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_one)
    TextView tvTitleRight;
    /**
     * 表示查找的图片
     */
    @Bind(R.id.iv_search)
    ImageView ivSearch;
    /**
     * 查找的输入框
     */
    @Bind(R.id.et_search_community)
    EditText etSearch;
    @Bind(R.id.tvNearComm)
    TextView tvNearComm;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.lv_select_community)
    PullToRefreshListView pullListView;
    private SelectCommunityListViewAdapter<Map<String, Object>> adapter;
    private String cityNameFromIntent = "";
    private String longitudeFromIntent;
    private String latitudeFromIntent;
    private List<Map<String, Object>> data = new ArrayList<>();
    private String desc = "";

    final  String MODULE_NAME="/app/guidePage/register/selComm";

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_select_community);
        ButterKnife.bind(this);
        getIntentInfo();
        initView();
        setAdapter();
        setXListViewAndEmptyLayoutListener(pullListView, emptyLayout, adapter);
    }

    /**
     * 数据采集体不要删除
     * @return
     */
    public Map<String,Object> getDataTrack(){
        Map<String,Object> map=new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    @Override
    protected void requestWhenPullRefresh() {
        getIntentInfo();/*默认由父类调用，所以需要在这里提前调用一下*/
        String cityName;
        String longitude;
        String latitude;
        cityName = cityNameFromIntent;
        longitude = longitudeFromIntent;
        latitude = latitudeFromIntent;
        CommunityHttpBiz.getCommunityList(cityName, desc, longitude, latitude, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                ArrayList data = (ArrayList) CommunityHttpBiz.handleCommunityList(response);
                handleAfterRequest(isConnected(false), OrangeHttpBiz.getTotalNum(response), data, pullListView, adapter);
            }
        }, pageNo, pageSize);
    }

    private void setAdapter() {
        adapter = new SelectCommunityListViewAdapter<>(this,
                data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                desc = etSearch.getText().toString();
                requestCommListWithResetPageNo();
                hideInput(v);
                break;
        }
    }

    private void initView() {
        tvNearComm.setVisibility(View.VISIBLE);
        tvTitle.setText(cityNameFromIntent);
        tvTitleRight.setVisibility(View.GONE);
        ivSearch.setOnClickListener(this);
        pullListView.setOnItemClickListener(itemListener);
        pullListView.setFootHintTextNoData("橙子君正在努力开通更多小区...");
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                /* 取最后一个字符，如果输入的是空字符串，则不处理 */
                if (!"".equals(keyword)) {
                    String lastChar = keyword.substring(keyword.length() - 1).trim();
                    if (lastChar.equals("")) {
                        return;
                    }
                }
                desc = keyword;
                requestCommListWithResetPageNo();
            }
        });
    }

    /**
     * 在按搜索键、软键盘搜索键、输入自动搜索的时候，需要将页码重置（上拉加载之后），否则会出现重复数据
     */
    private void requestCommListWithResetPageNo() {
        resetPageToDefault();
        requestWhenPullRefresh();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            /*隐藏软键盘*/
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(SelectCommunityActivity.this.getCurrentFocus().getWindowToken(), 0);
            }
            desc = etSearch.getText().toString();
            requestCommListWithResetPageNo();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            position = position - 1;
            if (position == -1) {
                return;
            }
            if (data.get(position) != null) {
                saveCommInfo(data.get(position));
                dataTrack(String.valueOf(data.get(position)));
                jumpToMain();
                setJPushTag(String.valueOf(data.get(position).get("comm")), String.valueOf(data.get(position).get("commID")));
            }
        }
    };


    private void dataTrack(String commName){
        Map<String,Object> map=new HashMap<>();
        map.put("commName",commName);
        DataTrack.clickTrack("btnComm",map);
    }


    /**
     * 点击跳转，并保存小区信息
     */
    private void saveCommInfo(Map<String, Object> commMap) {
        CommSp2.setCityName(String.valueOf(commMap.get("city")));

        CommSp2.setCommID(String.valueOf(commMap.get("commID")));
        CommSp2.setCommPmPhone(String.valueOf(commMap.get("phone")));
        CommSp2.setCommName(String.valueOf(commMap.get("comm")));
        CommSp2.setDistrictID(String.valueOf(commMap.get("districtID")));
        CommSp2.setStreet(String.valueOf(commMap.get("stree")));
        requestCustomerServicePhone();/*请求该小区的物业电话，为什么不放在小区信息里呢？*/
    }

    /**
     * 请求物业电话
     */
    private void requestCustomerServicePhone() {
        CommSp2.setCustomerServicePhone("");/*请求新橙子客服电话之前，先清除*/
        MainHttpBz.getCustomerServicePhone();
    }

    private void setJPushTag(String commName, String commID) {
        JPushTagHelper.getInstance().setContext(this);
        JPushTagHelper.getInstance().setTag(commName);
        JPushTagHelper.getInstance().setTag(commID);
    }

    public void jumpToMain() {
        CommonJumper.jumpToMain(this);
        finish();
    }

    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        // edit.setCursorVisible(false);//失去光标
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    Bundle bundle;

    private void getIntentInfo() {
        if (bundle == null) {
            bundle = getIntent().getExtras();
            cityNameFromIntent = bundle.getString("cityName");
            longitudeFromIntent = bundle.getString("longitude");
            latitudeFromIntent = bundle.getString("latitude");
        }
    }

    @Override
    protected EmptyLayout getEmptyLayout() {
        return emptyLayout;
    }

    @Override
    protected List getData() {
        return data;
    }

    @Override
    protected int getDataCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    protected void onDestroy(){

        super.onDestroy();
    }

}